package com.liruo.treasureattic.gateway.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liruo.treasureattic.common.httpmsg.result.BaseResponse;
import com.liruo.treasureattic.common.httpmsg.result.Errno;
import org.slf4j.Logger;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @Author:liruo
 * @Date:2022-10-09-11:07:12
 * @Desc
 */
public class HttpUtil {
    public static void setJsonContent(ServerHttpResponse resp){
        resp.getHeaders().setContentType(MediaType.APPLICATION_JSON);
    }
    public static Mono<Void> writeJsonResult(ServerHttpResponse resp,  byte[] body){
        setJsonContent(resp);
        return resp.writeWith(Mono.fromSupplier(() -> {
                DataBufferFactory bufferFactory = resp.bufferFactory();
                //todo 返回响应结果，根据业务需求，自己定制
                return bufferFactory.wrap(body);
            }
        ));
    }


    public static Mono<Void> writeJsonResultAndHandlerJacksonErr(ObjectMapper objectMapper,Logger log,  ServerHttpResponse resp, Exception e){
        setJsonContent(resp);
        try {
            return HttpUtil.writeJsonResult(resp,
                    objectMapper.writeValueAsBytes(BaseResponse.fail(
                            HttpStatus.FORBIDDEN.value(),
                            e.getMessage()
                    ))
            );
        } catch (JsonProcessingException err) {
            log.info("Error writing response，err=", err);
            err.printStackTrace();
            return HttpUtil.writeJsonResult(resp, Errno.SYSTEM.toString().getBytes(StandardCharsets.UTF_8));
        }
    }


    public static Mono<Void> writeJsonResultAndHandlerJacksonErrWithResult(
            ObjectMapper objectMapper, Logger log,
            ServerHttpResponse resp, BaseResponse<String> baseResponse){
        setJsonContent(resp);
        try {
            return HttpUtil.writeJsonResult(resp, objectMapper.writeValueAsBytes(baseResponse));
        } catch (JsonProcessingException err) {
            log.info("Error writing response，err=", err);
            err.printStackTrace();
            return HttpUtil.writeJsonResult(resp, Errno.SYSTEM.toString().getBytes(StandardCharsets.UTF_8));
        }
    }

}
